package com.sso.action.sys;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.sso.common.ConstantDate;
import com.sso.exception.SelectException;
import com.sso.manager.SysResourceManager;
import com.tools.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sso.action.BaseAction;
import com.sso.common.enums.FlagStatus;
import com.sso.entity.SysMenu;
import com.sso.entity.SysResource;
import com.sso.manager.SysMenuManager;
import com.sso.sys.annotation.ResourceInfo;

@Controller
@RequestMapping("/menu")
public class SysMenuAction extends BaseAction {

    @Autowired
    private SysMenuManager menuManager;
    @Autowired
    private SysResourceManager resManager;

    /**
     * 菜单管理页面
     * @return view
     */
    @ResourceInfo(cname = "菜单管理", ename = "menu.menuView")
    @RequestMapping("gotoMenuManagerView")
    public ModelAndView sysMenuView() {
        ModelAndView view = new ModelAndView("/manager/menuManager");
        return view;
    }

    /**
     * 保存修改菜单
     * @param menu
     * @param response
     * @reutrn JSON
     */
    @ResourceInfo(cname = "增加修改菜单", ename = "")
    @RequestMapping("saveMenu")
    public void saveMenu(SysMenu menu, HttpServletResponse response) {
        String s = PropertiesUtils.getValueByProperty("xssCode");
        BeanUtils.checkBean(menu);
        String flag = FlagStatus.ERROR.value;
        if (StrUtils.isEmpty(menu.getCname())) {
            this.outputJson(flag, "请输入菜单中文名称", response);
            return;
        }
        if (StrUtils.isEmpty(menu.getEname())) {
            this.outputJson(flag, "请输入菜单英文标识", response);
            return;
        }
        if (menu.getSequence() == null) {
            this.outputJson(flag, "请选择菜单序列", response);
            return;
        }
        String result = this.checkMenu(menu);
        if(!FlagStatus.SUCCESS.value.equals(result)){
            this.outputJson(flag,result,response);
            return;
        }
        try {
            //保存
            flag = menuManager.save(menu);
            //保存失败
            if(FlagStatus.SUCCESS.value.equals(flag)){
                this.outputJson(FlagStatus.SUCCESS.value, "保存成功", response);
            }else {
                this.outputJson(FlagStatus.ERROR.value,"保存失败",response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.outputJson(flag, "保存失败，请设联系管理人员", response);
        }
    }

    /**
     * 根据id查询数据，返回JSON
     * @param id
     * @param request
     * @param response
     * @throws SelectException
     */
    @RequestMapping("getMenuById")
    public void getMenuById(String id, HttpServletRequest request, HttpServletResponse response) throws SelectException {
        SysMenu menu = menuManager.selectById(id);
        String attributeStr = "id,cname,ename,sequence";
        String jsonStr = JSONUtils.toJsonInAttrbuite(menu, attributeStr);
        //JSONObject.toJSON()
        Object json = JSONObject.parse(jsonStr);
        this.outputJsonTrue(json, response);
    }

    /**
     * 查询的所有菜单数据
     * @param request
     * @param response
     * @return JSON
     */
    @RequestMapping("getMenuToJSON")
    public void getMenuList(HttpServletRequest request, HttpServletResponse response) {
        List<SysMenu> list = menuManager.selectByProperty(null);
        String attributeStr = "id,cname,parentMenuId";
        Object jsonArr = JSONObject.parse(JSONUtils.toJsonInAttrbuite(list, attributeStr));
        this.outputJson(FlagStatus.SUCCESS.value,jsonArr, response);
    }

    /**
     * 删除菜单
     * @param id
     * @param request
     * @param response
     * @return JSON
     */
    @RequestMapping("delMenu")
    public void delMenuLById(String id, HttpServletRequest request, HttpServletResponse response) {
        SysMenu menu = menuManager.selectById(id);
        if (menu == null) {
            this.outputJson(FlagStatus.ERROR.value, "未查询到要删除的菜单", response);
            return;
        }
        try {
            menuManager.deleteById(menu);
            this.outputJson(FlagStatus.SUCCESS.value, "删除成功", response);
        } catch (Exception e) {
            this.outputJson(FlagStatus.ERROR.value, "操作失败,请联系管理人员", response);
        }
    }

    /**
     * 菜单绑定资源
     * @param request
     * @param response
     * @return JSON
     */
    @RequestMapping("bindResource")
    public void bindResource(HttpServletRequest request, HttpServletResponse response) {
        String status = FlagStatus.ERROR.value;
        try {
            Map<String, Object> filterMap = RequestUtils.getParametersToMap(request, "");
            if (filterMap.get("menuId") == null || StrUtils.isEmpty(filterMap.get("menuId").toString())) {
                this.outputJson(status, "请选择菜单", response);
                return;
            }
            if (filterMap.get("resId") == null || StrUtils.isEmpty(filterMap.get("resId").toString())) {
                this.outputJson(status, "未查询到要绑定的资源", response);
                return;
            }
            SysMenu menu = menuManager.selectById(filterMap.get("menuId").toString());
            if (menu == null || StrUtils.isEmpty(menu.getId())) {
                this.outputJson(status, "未查询到要绑定的菜单", response);
                return;
            }
            SysResource res = resManager.selectByid(filterMap.get("resId").toString());
            if (res == null || StrUtils.isEmpty(res.getId())) {
                this.outputJson(status, "未查询到要绑定的资源", response);
                return;
            }
            menuManager.bindResource(menu,res);
            this.outputJson(FlagStatus.SUCCESS.value, "绑定成功", response);
        } catch (Exception e) {
            this.outputJson(status, "绑定失败", response);
        }
    }

    /**
     * 解除菜单绑定的资源
     * @param request
     * @param response
     * @return JSON
     */
    @RequestMapping("unBindResource")
    public void unBindResource(HttpServletRequest request, HttpServletResponse response) {
        String status = FlagStatus.ERROR.value;
        try {
            String menuId = RequestUtils.getParameters(request,"menuId");
            if (StrUtils.isEmpty(menuId)) {
                this.outputJson(status, "请选择菜单", response);
                return;
            }
            SysMenu menu = menuManager.selectById(menuId);
            if (StrUtils.isEmpty(menu.getId())) {
                this.outputJson(status, "未查询到要解绑的菜单", response);
                return;
            }
            if(StrUtils.isEmpty(menu.getResourceId())){
                this.outputJson(status,"菜单没有绑定资源路径不能解除绑定",response);
                return;
            }
            menuManager.unBindRsource(menu);
            this.outputJson(FlagStatus.SUCCESS.value, "绑定成功", response);
        } catch (Exception e) {
            e.printStackTrace();
            this.outputJson(status, "操作失败，请联系管理人员", response);
        }
    }

    /**
     * 校验菜单数据
     * @param menu
     * @return T or 错误信息
     */
    private String checkMenu(SysMenu menu){
        SysMenu oldMenu = menuManager.selectByEname(menu.getEname());
        if(!StrUtils.equals(menu.getId(),oldMenu.getId()) && StrUtils.equals(menu.getEname(),oldMenu.getEname())){
            return "菜单英文标识已存在";
        }
        //中文标识存在重复，不校验中文标识
//            oldMenu = menuManager.selectByCname(menu.getCname());
        //当数据库有数据时 如果两者ID不相同
//            if(!StrUtils.equals(menu.getId(),oldMenu.getId()) && StrUtils.equals(menu.getCname(),oldMenu.getCname())){
//                return "菜单中文标识已存在";
//            }
        return FlagStatus.SUCCESS.value;
    }
}